/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.addon;

import cn.easyplatform.contexts.Contexts;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.EnvDo;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.entities.beans.task.TaskBean;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.log.LogManager;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.services.IProjectService;
import cn.easyplatform.type.DeviceType;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.StateType;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by shiny on 2017-10-13.
 */
public class CallbackCmd extends AbstractCommand<SimpleRequestMessage> {

    private final static Logger log = LoggerFactory.getLogger(CallbackCmd.class);

    /**
     * @param req
     */
    public CallbackCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        Map<String, String> data = (Map<String, String>) req.getBody();
        String projectId = data.remove("_SYS_PROJECT_ID_");
        String name = data.remove("_SYS_NAME_");
        String logic = data.remove("_SYS_LOGIC_ID_");
        String ip = data.remove("_SYS_ADDRESS_");
        if (projectId == null || name == null || logic == null)
            return new SimpleResponseMessage("E015", "project|name|logic is not empty.");
        IProjectService ps = (IProjectService) cc.getEngineConfiguration().getService(projectId);
        if (ps == null)
            return new SimpleResponseMessage("E016", projectId + " not found.");
        UserDo userInfo = new UserDo();
        userInfo.setId("SYS.PAY." + name);
        userInfo.setName(name);
        userInfo.setDeviceType(DeviceType.API);
        userInfo.setState(StateType.START);
        userInfo.setIp(ip == null ? "localhost" : ip);
        cc.setupEnv(new EnvDo(projectId,
                DeviceType.API, ps
                .getLanguages().get(0), null, null));
        cc.setUser(userInfo);
        LogManager.startUser(cc.getEngineConfiguration().getLogPath(), ps.getId(), userInfo);
        if (log.isDebugEnabled())
            log.debug("callback : {}", data);
        try {
            TaskBean tb = new TaskBean();
            tb.setId(name);
            tb.setName(name);
            tb.setVisible(false);
            tb.setProcessCode("R");
            WorkflowContext ctx = new WorkflowContext(tb, 0, null, null);
            cc.setWorkflowContext(ctx);
            for (Map.Entry<String, String> entry : data.entrySet())
                ctx.getRecord().setVariable(new FieldDo(entry.getKey(), FieldType.VARCHAR, entry.getValue()));
            cc.beginTx();
            String code = RuntimeUtils.eval(cc, logic, ctx.getRecord());
            if (!"0000".equals(code)) {
                cc.rollbackTx();
                return new SimpleResponseMessage(code,
                        cc.getMessage(code, ctx.getRecord()));
            }
            cc.commitTx();
        } catch (Exception e) {
            cc.rollbackTx();
            return MessageUtils.getMessage(e, log);
        } finally {
            cc.closeTx();
            cc.logout();
            Contexts.clear();
            LogManager.stopUser(userInfo);
        }
        return new SimpleResponseMessage();
    }
}
